package xgin

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

// 自动根据 header 头中的 Content-Type 进行绑定参数地址
//
//	c	请求结构数据
//	b	绑定数据，传入时请传入指针地址，以免绑定后数据丢失
func Bind(c *gin.Context, b any) error {
	var err error
	if c.Request.Method == "GET" {
		err = c.ShouldBindWith(b, binding.Query)
	} else {
		switch c.ContentType() {
		case "application/json":
			err = c.ShouldBindBodyWith(b, binding.JSON)
		case "application/xml":
			err = c.ShouldBindBodyWith(b, binding.XML)
		default:
			err = c.ShouldBindWith(b, binding.Form)
		}
	}
	return err
}
